<html>
<head>
    <title>Golang 一对一聊天 </title>

    <script src="http://libs.baidu.com/jquery/1.4.2/jquery.min.js"></script>
    <meta charset="UTF-8" />
    <script type="text/javascript">

        $(function() {
            function rand(minNum, maxNum) {
                return Math.floor(Math.random()*(minNum - maxNum) + maxNum);
            }
            function sendId() {
                let timeStamp = (new Date()).valueOf();
                let randId = rand(100000, 999999);
                let id = timeStamp + "-" + randId;
                return id
            }
            function getUrlParam(name)
            {
                var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
                var r = window.location.search.substr(1).match(reg);  //匹配目标参数
                if (r!=null) return unescape(r[2]); return null; //返回参数值
            }
            var conn;
            var msg = $("#msg");
            var log = $("#log");
            uid=getUrlParam("uid");
            to_uid=getUrlParam("to_uid");
            groups_id=getUrlParam("groups_id");
            if (groups_id==null){
                groups_id="0"
            }
            function appendLog(msg) {
                var d = log[0]
                var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
                msg.appendTo(log)
                if (doScroll) {
                    d.scrollTop = d.scrollHeight - d.clientHeight;
                }
            }

            $("#form").submit(function() {
                if (!conn) {
                    return false;
                }
                if (!msg.val()) {
                    return false;
                }
                var json = {"seq": sendId(),"action":"sendmsg","data":{"userId":uid,"appId":1,"msgType":"text","toUid":to_uid,"groupsId":groups_id,"message":msg.val()}}
                // var json = {"sender":uid,"recipient":to_uid,"content":msg.val(),"typemsg":"1","appname":"1"}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串

                conn.send(jsonStr);
                appendLog($("<div/>").html('<div class="btalk"><span>' +msg.val()+'</span></div>'))
                msg.val("");
                return false
            });

            if (window["WebSocket"]) {
                conn = new WebSocket("ws://localhost:8282/ws?uid="+uid+"&to_uid="+to_uid+"&appname=1");
                conn.onopen = function(evt) {
                    console.log("Connection open ...");
                    console.log("用户准备登陆:" + uid);
                    conn.send('{"seq":"' + sendId() + '","action":"login","data":{"userId":"' + uid + '","appId":1,"toUid":"'+to_uid+'","groupsId":"'+groups_id+'"}}');

                    // 定时心跳
                    setInterval(heartbeat, 30 * 1000)
                };
                conn.onclose = function(evt) {
                    appendLog($("<div><b>Connection Closed.</b></div>"))
                }

                conn.onmessage = function(evt) {
                    console.log(evt.data)
                    obj = JSON.parse(evt.data);
                    if (obj.code !=undefined && obj.code!=200)
                    {
                        appendLog($("<div/>").text("发送失败"))
                    }else{
                        if (obj.action =="login")
                        {
                            appendLog($("<div/>").text("登录成功"))
                        }else if(obj.data!=undefined && obj.data.action =="sendmsg"){
                            appendLog($("<div/>").html("<div class=\"atalk\"><span>用户:</span>"+obj.data.content+"</div>"))
                        }
                    }
                }
                // 心跳
                function heartbeat() {
                    // console.log("定时心跳:" + uid);
                    conn.send('{"seq":"' + sendId() + '","action":"heartbeat","data":{}}');

                }
            } else {
                appendLog($("<div><b>WebSockets Not Support.</b></div>"))
            }
        });
    </script>
    <style type="text/css">
        html {
            overflow: hidden;
        }

        body {
            overflow: hidden;
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100%;
            background: gray;
        }
        .atalk {
            margin: 10px;
        }
        .atalk span {
            display: inline-block;
            background: #0181cc;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
            max-width: 200px;
            white-space: pre-wrap;
            text-align: left;
        }
        #log {
            background: white;
            margin: 0;
            padding: 0.5em 0.5em 0.5em 0.5em;
            position: absolute;
            top: 0.5em;
            left: 0.5em;
            right: 0.5em;
            bottom: 3em;
            overflow: auto;
        }

        #form {
            padding: 0 0.5em 0 0.5em;
            margin: 0;
            position: absolute;
            bottom: 1em;
            left: 0px;
            width: 100%;
            overflow: hidden;
        }
        .btalk {
            margin: 10px;
            text-align: right;
        }
        .btalk img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            float: right;
            margin-top: -10px;
        }
        .btalk span {
            display: inline-block;
            background: grey;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
            max-width: 200px;
            white-space: pre-wrap;
            text-align: left;
        }
    </style>
</head>
<body>
<div id="log"></div>
<form id="form">
    <input type="submit" value="发送" />
    <input type="text" id="msg" size="64"/>
</form>
</body>
</html>